package leetcode101.ch5;

public class NumberOfIslands {
    static int R;
    static int C;
    static char[][] G;

    public int numIslands(char[][] grid) {
        G = grid;
        R = G.length;
        C = G[0].length;
        int num = 0;

        for (int r = 0; r < R; r++) {
            for (int c = 0; c < C; c++) {
                if(dfs(r, c) != 0){
                    num++;
                }
            }
        }
        return num;

    }

    private boolean inArea(int r, int c) {
        return r >= 0 && c >= 0 && r < R && c < C;
    }

    private int dfs(int r, int c) {
        if (!inArea(r, c) || G[r][c] == '0') {
            return 0;
        }
        G[r][c] = '0'; //沉岛
        return 1 + dfs(r + 1, c)
                + dfs(r - 1, c)
                + dfs(r, c + 1)
                + dfs(r, c - 1 );
    }



    public static void main(String[] args) {
        char[][] grid = new char[][]{
                {'1','1','1','1','0'},
                {'1','1','0','1','0'},
                {'1','1','0','0','0'},
                {'0','0','0','0','0'}};
        int num = new NumberOfIslands().numIslands(grid);
        System.out.println(num);

    }
}
